<?php

class types_TypeManager {
    function __construct() {
        $this->types = array();
        $this->table_2_type = array();

        $this->load_types_from_db_();
    }

    function get_type($type) { 
        if (array_key_exists($type, $this->types)) {
            return $this->types[$type];
        } 
        return false;
    }

    function handled_table($table) {
        return array_key_exists($table, $this->table_2_type);
    }

    function table_type($table) {
        if (! array_key_exists($table, $this->table_2_type)) {
            return false;
        }

        // XXX/bowei -- for now we assume only 1 type per table
        assert(sizeof($this->table_2_type[$table]) == 1);
        return $this->types[$this->table_2_type[$table][0]];
    }

    function load_types_from_db_() {
        $r = mysql_query('SELECT * FROM neon_atom_types');
        if (! $r) {
            return;
        }
        
        while ($t = mysql_fetch_object($r)) {
            $table_desc = new types_TableDesc($t->tablename, 
                                              $t->intersect_query,
                                              split(' ', $t->intersect_fields),
                                              $t->guid_field);
            if (! array_key_exists($t->type, $this->types)) {
                $this->types[$t->type] = new types_AtomType($t->type);
            }
            
            $this->types[$t->type]->tables[$t->tablename] = $table_desc;
            if (! array_key_exists($t->tablename, $this->table_2_type)) {
                $this->table_2_type[$t->tablename] = array();
            }
            array_push($this->table_2_type[$t->tablename], $t->type);
        }
    }
}

class types_AtomType {
    function __construct($name) {
        $this->name = $name;
        $this->tables = array();
    }

    function add_table_desc($table_desc) {
        $this->tables[$table_desc->name] = $table_desc;
    }
}

class types_TableDesc {
    function __construct($name, $intersect_query, 
                         $intersect_fields, $guid_field) {
        $this->name             = $name;
        $this->intersect_query  = $intersect_query;
        $this->intersect_fields = $intersect_fields;
        $this->guid_field       = $guid_field;

        if ($this->guid_field == '') {
            $this->guid_field = 'guid';
        }
    }

    function intersect_query($values) {
        $query_values = array();
        foreach ($this->intersect_fields as $f) {
            array_push($query_values, $values->$f);
        }
         
        // XXX/bowei escape strings???
        return vsprintf($this->intersect_query, $query_values);
    }
}

?>